package org.linlinjava.litemall.admin.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.dto.TemplateData;
import org.linlinjava.litemall.admin.vo.WxMssVo;
import org.linlinjava.litemall.admin.web.AdminGoodsController;
import org.linlinjava.litemall.core.config.WxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class wxSendMessage {

    private final Log logger = LogFactory.getLog(wxSendMessage.class);

    @Autowired
    private Environment environment;
    /*
     * 发送订阅消息
     * */

    public Object pushAudit(String weixinOpenid,String type,Boolean results,String approveRemark){
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(weixinOpenid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(environment.getProperty("litemall.wx.audit-template-id"));//订阅消息模板id
        //        wxMssVo.setPage("pages/index/index");

        if(environment.getProperty("litemall.wx.env").equals("production")){
            wxMssVo.setData(proAuditData(type,results,approveRemark));
        }else {
            wxMssVo.setData(depAuditData(type,results,approveRemark));
        }
        return push(wxMssVo);
    }

    public Object pushState(String weixinOpenid,String shopName,String herbName){
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(weixinOpenid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(environment.getProperty("litemall.wx.state-template-id"));//订阅消息模板id
        //        wxMssVo.setPage("pages/index/index");

        if(environment.getProperty("litemall.wx.env").equals("production")){
            wxMssVo.setData(proStateData(shopName,herbName));
        }else {
            wxMssVo.setData(depStateData(shopName,herbName));
        }
        return push(wxMssVo);
    }

    public Object push(WxMssVo wxMssVo) {
        //发送订阅消息
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+getAccessToken();

        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        logger.info("wxPush:"+responseEntity.getBody());
        return responseEntity.getBody();
    }

    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", environment.getProperty("litemall.wx.app-id"));  //
        params.put("APPSECRET", environment.getProperty("litemall.wx.app-secret"));  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        Map<String,Object> map =StringToMap(body);
        String Access_Token = map.get("access_token").toString();
        return Access_Token;
    }

    public static Map<String,Object> StringToMap(String param){
        Map<String,Object> map = new HashMap<>();
        String s1 = param.replace("{","");
        String s2 = s1.replace("}","");
        String s3 = s2.trim();
        String[] split = s3.split(",");
        for (int i = 0;i<split.length;i++){
            String trim = split[i].trim();
            String[] split1 = trim.split(":");
            map.put(split1[0].replace("\"",""),split1[1].replace("\"",""));
        }
        return map;
    }

    public Map<String, TemplateData> depAuditData(String type,Boolean results,String approveRemark){
        Map<String, TemplateData> hashMap = new HashMap<>(4);
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String createdate = sdf.format(date);
        //这里是发送消息的内容，map里面的key值必须和设置推送模板消息一致

        hashMap.put("phrase5",new TemplateData(results?"通过":"驳回"));
        hashMap.put("date2",  new TemplateData(createdate));
        hashMap.put("thing1", new TemplateData(type));
        hashMap.put("thing4", new TemplateData(approveRemark));//消息内容
        return hashMap;
    }

    public Map<String, TemplateData> proAuditData(String type,Boolean results,String approveRemark){
        Map<String, TemplateData> hashMap = new HashMap<>(4);
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String createdate = sdf.format(date);
        //这里是发送消息的内容，map里面的key值必须和设置推送模板消息一致
        //说明
        hashMap.put("thing1",new TemplateData(type));
        //结果
        hashMap.put("thing2", new TemplateData(results?"通过":"驳回") );
        //时间
        hashMap.put("time4", new TemplateData(createdate) );
        //内容
        hashMap.put("thing5", new TemplateData(approveRemark));//消息内容
        return hashMap;
    }

    public Map<String, TemplateData> depStateData(String shopName,String herbName){
        Map<String, TemplateData> hashMap = new HashMap<>(4);
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String createdate = sdf.format(date);
        //这里是发送消息的内容，map里面的key值必须和设置推送模板消息一致
        //商家名称
        hashMap.put("thing16",new TemplateData(shopName));
        //商品名称
        hashMap.put("thing9", new TemplateData(herbName));
        //订单状态
        hashMap.put("phrase3", new TemplateData("已中标") );
        //更新时间
        hashMap.put("time11", new TemplateData(createdate));
        return hashMap;
    }

    public Map<String, TemplateData> proStateData(String shopName,String herbName){
        Map<String, TemplateData> hashMap = new HashMap<>(4);
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String createdate = sdf.format(date);
        //这里是发送消息的内容，map里面的key值必须和设置推送模板消息一致
        //商家名称
        hashMap.put("thing4",new TemplateData(shopName));
        //商品名称
        hashMap.put("thing10", new TemplateData(herbName) );
        //订单状态
        hashMap.put("phrase6", new TemplateData("已中标"));
        //更新时间
        hashMap.put("time7", new TemplateData(createdate));//消息内容
        return hashMap;
    }


}
